package org.example.controller;

import org.apache.ibatis.annotations.Param;
import org.example.domain.LastArticle;
import org.example.service.impl.LastArticleServiceImpl;
import org.example.untils.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("lastArticle")
public class LastArticleController {

    @Autowired
    private LastArticleServiceImpl lastArticleServiceImpl;

    @GetMapping("/getPictureByArticleLink")//管理员新增往期推文时爬取封面
    public Result getPictureByArticleLink(@Param("articleLink") String articleLink) throws IOException {//通过文章链接拉取图片，此处不是很熟悉，
        // 不作分层以方便编写
        Document document;
        document = Jsoup.connect(articleLink).get();
        //获取网站的document对象
        Elements images = document.select("img");//获取其中的图片
        Elements text = document.select("meta");//获取标题
        String[] srcsAndTitle=new String[5];
        int start=0;//开始截取的位置
        for (;!images.get(start).toString().contains("data-src=\"");start++){//前往到正确的有图片的位置

        }
        String srcOne=images.get(start).toString().split("data-src=\"")[1].split("\" data-type=\"")[0];
        String srcTwo=images.get(start+1).toString().split("data-src=\"")[1].split("\" data-type=\"")[0];
        String srcThree=images.get(start+2).toString().split("data-src=\"")[1].split("\" data-type=\"")[0];
        String srcFour=images.get(start+3).toString().split("data-src=\"")[1].split("\" data-type=\"")[0];
        String title=text.get(12).toString().split("content=\"")[1].split("\">")[0];
        srcsAndTitle[0]=srcOne;
        srcsAndTitle[1]=srcTwo;
        srcsAndTitle[2]=srcThree;
        srcsAndTitle[3]=srcFour;
        srcsAndTitle[4]=title;
        return new Result(200,"拉取成功",srcsAndTitle);
    }

    @PostMapping("/addLastArticle")
    private Result addLastArticle(@RequestBody() LastArticle lastArticle){
        lastArticleServiceImpl.addLastArticle(lastArticle);
        return new Result(200,"新增成功",null);
    }

    @GetMapping("/getLastArticleLimit")
    private Result getLastArticleLimit(@Param("start") Integer start,@Param("start") Integer number){
        LastArticle[] lastArticles=lastArticleServiceImpl.getLastArticleLimit(start,number);
        return new Result(200,"获取成功",lastArticles);
    }

}
